package com.wzq.shiro.shirodemo.realm;

import com.wzq.shiro.shirodemo.entity.User;
import com.wzq.shiro.shirodemo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author wzq
 * @date 2020/5/26
 * @DESC 用户realm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 重写认证方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1,获取用户手机号和密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String pwd = String.valueOf(usernamePasswordToken.getPassword());
        // 2,根据手机号查询用户
        User user = userService.queryUserByPhone(usernamePasswordToken.getUsername());
        if (user == null){
            return null;
        }
        // 返回null 会抛出异常
        return new SimpleAuthenticationInfo(user,pwd,"");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
